package com.xiyu.service.repository.material.stock;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.stock.*;
import com.xiyu.service.vo.material.stockOut.StockOutPageQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface MaterialStockOutRepository extends JRepository<MaterialStockOut, Long> {
    MaterialStockOutTable materialStockOutTable = MaterialStockOutTable.$;

    default Page<MaterialStockOut> pageQuery(StockOutPageQueryInput inputVO){
        return sql().createQuery(materialStockOutTable)
                .whereIf(inputVO.getStatus() != null, () -> materialStockOutTable.status().in(inputVO.getStatus()))
                .whereIf(StringUtils.hasText(inputVO.getStockOutNo()), () -> materialStockOutTable.stockOutNo().like(inputVO.getStockOutNo()))
                .whereIf(inputVO.getWarehouseId() != null, materialStockOutTable.warehouseId().eq(inputVO.getWarehouseId()))
                .orderBy(materialStockOutTable.id().desc())
                .select(materialStockOutTable)
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<MaterialStockOut> findDetailById(Long id){
        return sql().createQuery(materialStockOutTable)
                .where(materialStockOutTable.id().eq(id))
                .select(materialStockOutTable.fetch(
                        MaterialStockOutFetcher.$.allTableFields().details(
                                MaterialStockOutDetailFetcher.$.allTableFields().material(
                                        MaterialInfoFetcher.$.allTableFields().category(
                                                MaterialCategoryFetcher.$.allTableFields()
                                        )
                                )
                        )
                )).fetchOptional();
    }

}